package com.huibao.hulibao.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.RelativeLayout;

import com.apkfuns.logutils.LogUtils;
import com.huibao.hulibao.R;
import com.huibao.hulibao.activity.HuliDetailActivity;
import com.huibao.hulibao.activity.LoginActivity;
import com.huibao.hulibao.activity.MainActivity;
import com.huibao.hulibao.activity.WebViewActivity;
import com.huibao.hulibao.adapter.HuLiViewPgaerAdapter;
import com.huibao.hulibao.adapter.HuliGvAdapter;
import com.huibao.hulibao.constant.GlobalConstants;
import com.huibao.hulibao.constant.PermissionConstants;
import com.huibao.hulibao.entity.HuLiEntity;
import com.huibao.hulibao.entity.LoginEntity;
import com.huibao.hulibao.entity.WebEntity;
import com.huibao.hulibao.utils.PreUtils;
import com.huibao.hulibao.utils.T;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by lizhaoyong on 2018/5/7.
 */
public class HuliFragmentView extends Fragment {
    private Unbinder unbinder;

    private Context context;
    @BindView(R.id.rl_mom)
    RelativeLayout rl_mom;
    @BindView(R.id.rl_baby)
    RelativeLayout rl_baby;
    @BindView(R.id.vp_huli)
    ViewPager vp_huli;

    private HuLiViewPgaerAdapter hvpa;
    // 妈妈护理
    private View v_mom;
    private GridView gv_mom;
    // 宝宝护理
    private View v_baby;
    private GridView gv_baby;
    private ArrayList<View> al_views;

    private LoginEntity le;
    private MainActivity mainActivity;

    // 数据请求成功否
    private boolean is_mom_data = false;
    private boolean is_baby_data = false;

    @OnClick({R.id.rl_mom, R.id.rl_baby})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_mom:
                momViewSelected();
                vp_huli.setCurrentItem(0);
                break;
            case R.id.rl_baby:
                babyViewSelected();
                vp_huli.setCurrentItem(1);
                break;
        }
    }

    @OnClick(R.id.tv_hulijilu)
    public void hulijilu() {
        Intent intent = new Intent(getActivity(), WebViewActivity.class);
        intent.putExtra("url", GlobalConstants.HOST + "AppWap/PDA_APP/WebTools/ShowNurseRecords.aspx?ss=" + le.Message.Session);
        startActivity(intent);
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_huli, null);
        unbinder = ButterKnife.bind(this, v);
        context = getActivity();
        mainActivity = (MainActivity) getActivity();

        le = (LoginEntity) PreUtils.getObject(context, "LoginEntity");

        getHuliDataFromSever(1);

        initViewPager(inflater);
        vp_huli.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 0) {
                    momViewSelected();
                    if (is_mom_data == false) {
                        getHuliDataFromSever(1);
                    }
                } else {
                    babyViewSelected();

                    if (is_baby_data == false) {
                        getHuliDataFromSever(2);
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        return v;
    }

    // 初始化viewpager
    public void initViewPager(LayoutInflater inflater) {
        v_mom = inflater.inflate(R.layout.vp_mom_huli, null);
        v_baby = inflater.inflate(R.layout.vp_baby_huli, null);
        gv_mom = (GridView) v_mom.findViewById(R.id.gv_mom_huli);
        gv_baby = (GridView) v_baby.findViewById(R.id.gv_baby_huli);
        // 取消点击颜色
        gv_mom.setSelector(new ColorDrawable(Color.TRANSPARENT));
        gv_baby.setSelector(new ColorDrawable(Color.TRANSPARENT));

        al_views = new ArrayList<View>();
        al_views.add(v_mom);
        al_views.add(v_baby);
        hvpa = new HuLiViewPgaerAdapter(al_views);
        vp_huli.setAdapter(hvpa);
    }

    // 妈妈护理被选中的样式
    public void momViewSelected() {
        rl_mom.setBackground(getResources().getDrawable(R.drawable.corner_view_nurse_title_selected));
        rl_baby.setBackground(getResources().getDrawable(R.drawable.corner_view_nurse_title_no_selected));
    }

    // 宝宝护理被选中的样式
    public void babyViewSelected() {
        rl_mom.setBackground(getResources().getDrawable(R.drawable.corner_view_nurse_title_no_selected));
        rl_baby.setBackground(getResources().getDrawable(R.drawable.corner_view_nurse_title_selected));
    }


    // 获取护理数据
    public void getHuliDataFromSever(final int type) {
        if (le == null) {
            return;
        }

        RequestParams params = new RequestParams(GlobalConstants.URL);
        params.setCacheMaxAge(0);
        mainActivity.showDialog();
        JSONObject object = new JSONObject();
        try {
            object.put("type", type);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        params.addBodyParameter("q", le.Message.Session + GlobalConstants.URL_HULI + object.toString());
        LogUtils.d("params = " + params.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                mainActivity.closeDialog();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(result);
                    LogUtils.d("json = " + jsonObject.toString());
                    // 登录超时
                    if (jsonObject.toString().contains("\"State\"" + ":" + "\"" + GlobalConstants.LOGIN_TIME_OUT + "\"")) {
                        // 退出登录
                        PreUtils.saveObject(context, "LoginEntity", null);
                        Intent intent = new Intent(context, LoginActivity.class);
                        startActivity(intent);
                        getActivity().finish();
                        return;
                    }

                    final HuLiEntity he = GlobalConstants.gson.fromJson(jsonObject.toString(), HuLiEntity.class);
                    if (he != null && he.State.equals(GlobalConstants.SUCCESS_CODE)) {
                        if (type == 1) {
                            is_mom_data = true;
                            gv_mom.setAdapter(new HuliGvAdapter(context, he.Message, type));
                            gv_mom.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                    if (le.Message.Powers.contains(PermissionConstants.HULI)) {
                                        Intent intent = new Intent(context, HuliDetailActivity.class);
                                        intent.putExtra("type", String.valueOf(type));
                                        intent.putExtra("mom_data", he.Message.get(i));
                                        intent.putExtra("pic", he.Message.get(i).m);
                                        intent.putExtra("session", le.Message.Session);
                                        startActivity(intent);
                                    } else {
                                        T.show(getActivity(), "您没有 " + PermissionConstants.getPowerName(PermissionConstants.HULI) + " 权限！", 0);
                                    }
                                }
                            });
                        } else if (type == 2) {
                            is_baby_data = true;
                            gv_baby.setAdapter(new HuliGvAdapter(context, he.Message, 2));
                            gv_baby.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                    if (le.Message.Powers.contains(PermissionConstants.HULI)) {
                                        Intent intent = new Intent(context, HuliDetailActivity.class);
                                        intent.putExtra("type", String.valueOf(type));
                                        intent.putExtra("pic", he.Message.get(i).m);
                                        intent.putExtra("mom_data", he.Message.get(i));
                                        intent.putExtra("session", le.Message.Session);
                                        startActivity(intent);
                                    } else {
                                        T.show(getActivity(), "您没有 " + PermissionConstants.getPowerName(PermissionConstants.HULI) + " 权限！", 0);
                                    }

                                }
                            });
                        }
                    }

                    // LogUtils.d("result = " + jsonObject.toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mainActivity.closeDialog();

            }

            @Override
            public void onCancelled(CancelledException cex) {
                mainActivity.closeDialog();
            }

            @Override
            public void onFinished() {
                mainActivity.closeDialog();
            }
        });

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
